from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from.forms import CustomUserCreationForm, CustomUserChangeForm
from.models import CustomUser


# 用户注册视图
def register(request):
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            messages.success(request, '恭喜你，注册成功！')
            return redirect('home')  # 假设首页名为 'home'
        else:
            messages.error(request, '注册信息填写有误，请检查后重新提交。')
    else:
        form = CustomUserCreationForm()
    return render(request, 'users/register.html', {'form': form})


# 用户登录视图
def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            messages.success(request, '登录成功！')
            return redirect('home')
        else:
            messages.error(request, "用户名或密码错误")
    return render(request, 'users/login.html', {'messages': messages.get_messages(request)})


# 用户登出视图
@login_required
def user_logout(request):
    logout(request)
    messages.success(request, '已成功登出。')
    return redirect('home')


# 用户个人信息编辑视图
@login_required
def edit_profile(request):
    if request.method == 'POST':
        form = CustomUserChangeForm(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, '个人信息修改成功。')
            return redirect('profile')  # 假设个人信息页面名为 'profile'
        else:
            messages.error(request, '信息修改出现问题，请检查填写内容后重新提交。')
    else:
        form = CustomUserChangeForm(instance=request.user)
    return render(request, 'users/edit_profile.html', {'form': form})